<?php

error_reporting(0);
@set_time_limit(1000);
ini_set("magic_quotes_runtime", 0);
date_default_timezone_set('PRC');
ini_set('memory_limit', '640M');
header('Content-type: text/html; charset=utf-8');
define('adminfile', 'install');
define('admin_ClassURL', 'http://' . $_SERVER['HTTP_HOST'] . substr($_SERVER['PHP_SELF'], 0, strrpos($_SERVER['PHP_SELF'], '/')));
define('admin_URL', str_replace('/' . adminfile, '/', admin_ClassURL));
define('admin_ROOT', substr(__FILE__, 0, strrpos(__FILE__, adminfile)));
define('admin_DIR', pathinfo(__FILE__, PATHINFO_DIRNAME));
require admin_ROOT . 'install/fun_center.php';
require admin_ROOT . 'install/class_db.php';
require admin_ROOT . 'install/lan_inc.php';
require admin_ROOT . 'install/sys_inc.php';
require admin_ROOT . 'public/ectemplates/ectemplates_class.php';
require admin_ROOT . 'public/class_json.php';

$ectemplates = new Ectemplates();
$ectemplates->tpl_dir = admin_ROOT . 'install/templates/';
$ectemplates->tpl_c_dir = admin_ROOT . 'install/templates_c/';
$ectemplates->cache_dir = admin_ROOT . 'install/templates_c/';
$ectemplates->dbcache_dir = admin_ROOT . 'install/templates_c/';
$ectemplates->caching = false;
$ectemplates->cache_time = 60 * 60 * 24;
$ectemplates->templatesfileex = '.html';
$ectemplates->left_delimiter = '[%';
$ectemplates->right_delimiter = '%]';

$ectemplates->libdir = 'lib_public.php';

$ectemplates->templatesDIR = '';
$step = intval(accept('step', 'R')) ? intval(accept('step', 'R')) : 0;
$ectemplates->assign('step', $step);
$ectemplates->assign('LAN', $LAN);
$ectemplates->assign('SOFT_VERSION', SOFT_VERSION);

if ($step == 3) {
	header("Location:../ydbsupervise/");
}
if (file_exists($installlock)) {
	message($LAN['install_errno_1000'], $LAN['install_errno_1045'], 0, 1);
}
if ($step == 0) {
	$ectemplates->display('step');
} elseif ($step == 1) {
	$ectemplates->assign('cp_items', syscheck($cp_items));
	$ectemplates->assign('dir_items', dircheck($dir_items));
	$ectemplates->assign('func_items', function_check($func_items));
	$ectemplates->display('step');
} elseif ($step == 2) {
	//$funchk = function_check($func_items);
	//foreach ($funchk as $fun) {
	//	if($fun['status'] !=1) {
	//		message("空间有不支持的组建", "对不起,您的空间不支持<font color='red'>".$fun['name']."</font>组件，请与管理员联系。");
	//		break;
	//	}
	//}
	$dirchk = dircheck($dir_items);
	foreach ($dirchk as $fun) {
		if($fun['status'] !=1) {
			message("目录不可写", "对不起,目录 <font color='red'>".$fun['path']."</font> 不可写，请与空间提供商联系。");
			break;
		}
	}
	@include CONFIG;
	$dbclass = intval(accept('dbclass', 'R')) ? intval(accept('dbclass', 'R')) : 0;
	if ($dbclass == 0) {
		$ectemplates->assign('domain', admin_URL);
		$ectemplates->display('step');
	} elseif ($dbclass == 1) {
		$dbhost = accept('dbhost', 'R');
		$dbname = accept('dbname', 'R');
		$dbuser = accept('dbuser', 'R');
		$dbpw = accept('dbpw', 'R');
		$tablepre = accept('tablepre', 'R');
		$username = accept('username', 'R');
		$password = accept('password', 'R');
		$password2 = accept('password2', 'R');
		$setupdbtype = accept('setupdbtype', 'R');
		$sitename = accept('sitename', 'R');
		$domain = accept('domain', 'R');
		$hotel_aid = accept('hotel_aid', 'R');
		$hotel_key = accept('hotel_key', 'R');
		$sms_aid = $hotel_aid;
		$sms_key = accept('sms_key', 'R');
		$is_html = accept('is_html', 'R');
		$file_htmldir = accept('file_htmldir', 'R');
		$is_caching = accept('is_caching', 'R');
		$is_anonymous = accept('is_anonymous', 'R');

		$setupcreatsql = "DROP TABLE `ydb_admin_member`, `ydb_admin_powergroup`, `ydb_bbs`, `ydb_bbs_content`, `ydb_bbs_label`, `ydb_bbs_typelist`, `ydb_calling`, `ydb_city`, `ydb_config`, `ydb_document`, `ydb_document_album`, `ydb_document_content`, `ydb_document_exhibition`, `ydb_document_label`, `ydb_document_other`, `ydb_document_value`, `ydb_enquiry`, `ydb_enquiry_info`, `ydb_form_attr`, `ydb_form_group`, `ydb_form_time`, `ydb_form_value`, `ydb_hotelcity`, `ydb_hotel_comment`, `ydb_hotel_order`, `ydb_keylink`, `ydb_keylink_type`, `ydb_lng`, `ydb_lngpack`, `ydb_logs`, `ydb_member`, `ydb_member_attr`, `ydb_member_class`, `ydb_member_value`, `ydb_menubotton`, `ydb_menulink`, `ydb_model`, `ydb_model_att`, `ydb_order`, `ydb_order_info`, `ydb_order_pay`, `ydb_order_payreceipt`, `ydb_order_shipping`, `ydb_order_shipreceipt`, `ydb_skin`, `ydb_subjectlist`, `ydb_templates`, `ydb_typelist`;";
		$setupcreatsql = str_replace(ORIG_TABLEPRE, $tablepre, $setupcreatsql);
		$version = "";
		$server = $_SERVER['SERVER_SOFTWARE'];
		if(substr($server,0,6)=="Apache") {
			$version = $server;
		} else {
			$version = $server ." PHP/".PHP_VERSION;
		}
		$api = $iscurl = function_exists('curl_exec')? "curl" : "file";
		$useragent = "YudingBao (".$version."; Ver/".SOFT_VERSION."; API/".$api."; http://www.yudingbao.com/);";
		$referer = $_SERVER['HTTP_REFERER'];
		$postlist = $_POST;
		if($hotel_aid !='' && $hotel_key !='') {
			
			$url = "http://api.yudingbao.net/v1.0/verify.ashx?aid=$hotel_aid&key=$hotel_key&ran=".rand();   //验证API
			$iscurl = function_exists('curl_exec')? true : false;  //是否支持curl
			if($iscurl) {
				$res = get_curl($url,$useragent,$referer);
			} else {
				$res = get_remotefile($url,$useragent,$referer);
			}
			$arr = array();
			$isjson = function_exists('json_decode')? true : false;
			if($isjson) {
				$arr = json_decode($res,true);
			} else {
				$json = new json();
				$arr = $json->jsonDecode($res);
			}
			if($arr['Status'] != 0) {
				message($LAN['install_errno_1046'], $LAN['install_api_text']);
			}
		}
		if($sms_aid !='' && $sms_key !='') {
			$url = "http://api.yudingbao.net/v1.0/verify.ashx?aid=$sms_aid&key=$sms_key&ran=".rand();   //验证API
			$iscurl = function_exists('curl_exec')? true : false;  //是否支持curl
			if($iscurl) {
				$res = get_curl($url,$useragent,$referer);
			} else {
				$res = get_remotefile($url,$useragent,$referer);
			}
			$arr = array();
			$isjson = function_exists('json_decode')? true : false;
			if($isjson) {
				$arr = json_decode($res,true);
			} else {
				$json = new json();
				$arr = $json->jsonDecode($res);
			}
			if($arr['Status'] != 0) {
				message($LAN['install_errno_1047'], $LAN['install_api_sms']);
			}
		}
		if (empty($dbname)) {
			message($LAN['dbname_invalid'], $LAN['dbnameempay']);
		} else {
			if (!@mysql_connect($dbhost, $dbuser, $dbpw)) {
				$errno = mysql_errno();
				$error = mysql_error();
				if ($errno == 1045) {
					message($LAN['database_errno_1045'], $error);
				} elseif ($errno == 2003) {
					message($LAN['database_errno_2003'], $error);
				} else {
					message($LAN['database_connect_error'], $error);
				}
			}
			if (mysql_get_server_info() > '4.1') {
				mysql_query("CREATE DATABASE IF NOT EXISTS `$dbname` DEFAULT CHARACTER SET " . DBCHARSET);
			} else {
				mysql_query("CREATE DATABASE IF NOT EXISTS `$dbname`");
			}
			if (mysql_errno ()) {
				message($LAN['database_errno_1044'], mysql_error());
			}
			mysql_close();
		}
		if (empty($dbname) || empty($password)) {
			message($LAN['admininfo_invalid'], $LAN['admin_invalid']);
		}
		
		$password = md5($password);
		$nowtime = time();

		config_edit($postlist);
		$db = new dbmysq;
		$db->connect($dbhost, $dbuser, $dbpw, $dbname, DBCHARSET);

		$sql = file_get_contents($sqlfile);

		$sql = str_replace("\r\n", "\n", $sql);
		$sql = str_replace("\r", "\n", str_replace("`" . ORIG_TABLEPRE, "`" . $tablepre, $sql));
		$sql = str_replace("预订宝酒店预订系统",$sitename,$sql);
		$sql = str_replace("http://www.lvvee.com/",$domain,$sql);
		$ret = array();
		$num = 0;
		foreach (explode(";\n", trim($sql)) as $query) {
			$ret[$num] = '';
			$queries = explode("\n", trim($query));
			foreach ($queries as $query) {
				$ret[$num] .= ( isset($query[0]) && $query[0] == '#') || (isset($query[1]) && isset($query[1]) && $query[0] . $query[1] == '--') ? '' : $query;
			}
			$num++;
		}
		unset($sql);
		show_install();
		if ($setupdbtype) {
			$db->query($setupcreatsql);
		}
		$i = 0;
		foreach ($ret as $query) {
			$query = trim($query);
			if ($query) {
				if (preg_match('/CREATE\s*TABLE\s*IF\s*NOT\s*EXISTS/', $query)) {
					//$name = preg_replace("/CREATE\s*TABLE\s*IF\s*NOT\s*EXISTS\s*`([a-zA-Z0-9_\n]+)`.*/is", "\\1", $query);
					$message = "数据结构安装成功...";
				} else {
					//$name = preg_replace("/INSERT\s*INTO\s*`([a-zA-Z0-9_\n]+)`.*/is", "\\1", $query);
					$message = "数据库正在加载中";
				}
				$i++;
				if($i % 100 == 0) {
					echo '<script type="text/javascript">showmessage(\'' . addslashes($message) . ' \');</script>' . "\r\n";
				}
				$db->query($query);
			}
		}
		$db->query("INSERT INTO " . $tablepre . "admin_member(username,password,name,sex,intotime,intime,outtime,ipadd,hit,powergroup,inputclassid,isclass) VALUES ('$username','$password','$username',1,$nowtime,$nowtime,$nowtime,0,0,1,1,1)");
		$db->query("UPDATE " . $tablepre . "config SET value='$domain' WHERE valname='domain'");
		$db->query("UPDATE " . $tablepre . "config SET value='$sitename' WHERE valname='sitename'");
		$db->query("UPDATE " . $tablepre . "config SET value='$is_html' WHERE valname='is_html'");
		$db->query("UPDATE " . $tablepre . "config SET value='$file_htmldir' WHERE valname='file_htmldir'");
		$db->query("UPDATE " . $tablepre . "config SET value='$is_caching' WHERE valname='is_caching'");
		$db->query("UPDATE " . $tablepre . "config SET value='$is_anonymous' WHERE valname='is_anonymous'");
		$db->query("UPDATE " . $tablepre . "lngpack SET langstr='$sitename' WHERE keycode='sitename'");
		$db->query("UPDATE " . $tablepre . "config SET value='$hotel_aid' WHERE valname='hotel_aid'");
		$db->query("UPDATE " . $tablepre . "config SET value='$hotel_key' WHERE valname='hotel_key'");
		$db->query("UPDATE " . $tablepre . "config SET value='$sms_aid' WHERE valname='sms_aid'");
		$db->query("UPDATE " . $tablepre . "config SET value='$sms_key' WHERE valname='sms_key'");
		$db->query("UPDATE " . $tablepre . "config SET value='[旅易中国]' WHERE valname='sms_text'");
		
		if (!file_exists($installlock)) {
			@touch(admin_ROOT . './datacache/install.lock');
		}
		$setupclass = true;
		if ($setupclass) {
			echo '<script type="text/javascript">document.getElementById("laststep").disabled=false;document.getElementById("laststep").value = \'安装成功\';</script>' . "\r\n";
		}
	}
}
?>